package com.GLM.Viewer.Circle;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

	public class CreateNewCircleMyFriendsViewActivity extends Activity{
		private final static int FRIENDLIST_LOADING = 111;
		private final static int FRIENDLIST_LONDED = 222;
		private ListView mFriendsList;
		private SimpleAdapter mFriendsAdapter;
		private List<Map<String, Object>> mFriendsItems = new ArrayList<Map<String, Object>>();
		private String[] friendsItemKeys = new String[] { "nickname", "location","remark"};
		private int[] friendsItemIds = new int[] { R.id.myfriendlistitem_nickname, R.id.myfriendlistitem_loc,R.id.friend_remark };
		private Map<String, String> friendsPics = new HashMap<String, String>();
		private Map<Integer, Integer> friendMap = new HashMap<Integer, Integer>();
		private AsynImageLoader imageLoader = new AsynImageLoader();
		private Set<String> friendSet = new HashSet<String>();
		private int[] friendIds;   
		private Button addButton;
		private boolean loadData = true;
		private int screenWidth;
		private int screenHeight;
		
		private Handler mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				Thread thread;
				switch (msg.what) {
				case FRIENDLIST_LOADING:
					mFriendsAdapter = null;
					thread = new Thread(new Runnable() {
						public void run() {
							
							initFriendsList();
							mFriendsAdapter = new SimpleAdapter(CreateNewCircleMyFriendsViewActivity.this, mFriendsItems, R.layout.view_myfriends_listitem, friendsItemKeys, friendsItemIds);
							mHandler.sendEmptyMessage(FRIENDLIST_LONDED);
						}
						 
					});
					thread.start();
					break;

				case FRIENDLIST_LONDED:
					if (mFriendsAdapter != null && mFriendsItems.size()>0) {
						mFriendsList.setAdapter(mFriendsAdapter);
						bindItemClick();
						
					}else{
						Paint paint = new Paint();
						paint.setTextSize(20);
						paint.setAntiAlias(true);
						String str = getString(R.string.friends_mygroup_nofriends);
						Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
						Canvas canvas = new Canvas(bitmap);
						
						canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
						FrameLayout layout = (FrameLayout)findViewById(R.id.myfriends_layout);
						Drawable drawable = new BitmapDrawable(bitmap);
						layout.setBackgroundDrawable(drawable);
					}
					break;
				}
			};
		};

		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			setContentView(R.layout.view_myfriends_list);
			screenWidth = getWindowManager().getDefaultDisplay().getWidth();
			screenHeight = getWindowManager().getDefaultDisplay().getHeight();
			mFriendsList = (ListView)findViewById(R.id.myfriendlist_listview);
			Intent intent = getIntent();
			friendIds = intent.getIntArrayExtra("friendIds");
			
			if(friendIds != null && friendIds.length>0){
				for(int i=0;i<friendIds.length; i++){
					friendSet.add(String.valueOf(friendIds[i]));
				}
			}
			addButton = (Button)findViewById(R.id.myfriendlist_selectFriends);
			addButton.setOnClickListener(clickListener);
			mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
		}

		
		public void bindItemClick(){
			mFriendsList.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View v, int position,
						long id) {
					// TODO Auto-generated method stub
					
					ImageView imageView = (ImageView)v.findViewById(R.id.friend_choose_imageview);
					if(imageView.getVisibility() == View.VISIBLE){
						imageView.setVisibility(View.INVISIBLE);
						friendSet.remove(String.valueOf(friendMap.get(position)));
					}else {
						imageView.setVisibility(View.VISIBLE);
						friendSet.add(String.valueOf(friendMap.get(position)));
					}
				}
			});
			
			mFriendsList.setOnScrollListener(scrollListener);
			
		}
		
		
		public OnClickListener clickListener = new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.myfriendlist_selectFriends:
					
					Intent intent = new Intent(CreateNewCircleMyFriendsViewActivity.this,CreateNewCircleViewActivity.class);
					int count = friendSet.size();
					Log.d("count", count + "");
					if (count > 0) {
						int[] Ids = new int[count];
						int i = 0;
						Iterator iterator = friendSet.iterator();
						while(iterator.hasNext()){
							Ids[i++] = Integer.valueOf((String)iterator.next());
						}
						intent.putExtra("chooseFriends", Ids);
					} else
						intent.putExtra("chooseFriends", "");
					setResult(RESULT_OK, intent);
					finish();
					break;

				default:
					break;
				}
			}
		};
		
		public OnScrollListener scrollListener = new OnScrollListener() {
			
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if(firstVisibleItem + visibleItemCount == totalItemCount){
					loadData = false;
				}
				LoadAdapterItemView();
				
			
			}
		};
		
		
		public void LoadAdapterItemView(){
			int selectId = mFriendsList.getSelectedItemPosition();
			int count = mFriendsList.getChildCount();
			for(int i=0; i<count; i++){
				View view = mFriendsList.getChildAt(i);
				ImageView chooseImage = (ImageView)view.findViewById(R.id.friend_choose_imageview);
				ImageView avarImageView = (ImageView)view.findViewById(R.id.myfriendlistitem_avatar);
				String picurl = friendsPics.get(String.valueOf(i));
				if(picurl != null && picurl != ""){
					Log.d("picurl", picurl);
					imageLoader.showImageAsyn(avarImageView, Constant.URL_USER_MIDDLE + picurl, R.drawable.glm_white);
				}
				int friId = friendMap.get(i);
				if(loadData && friendIds != null){
					int length = friendIds.length; 
					for(int j=0; j< length; j++){
						if(friendIds[j] == friId){
							chooseImage.setVisibility(View.VISIBLE);
							break;
						}
					}
				}
				if(i== count-1){
					loadData = false;
				}
			}
		}
		
		public void initFriendsList() {
			JSONObject jsonData = new JSONObject();
			JSONResponse jsonResponse = null;
			try {
				int userId = UserInfoDAO.getUserInfo(CreateNewCircleMyFriendsViewActivity.this).getUserId();
				jsonData.put(Constant.PARAM_USERID_ONE, userId);
				jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDLIST, jsonData);
				if (jsonResponse.getStatus() != Status.ERR) {
					int status = -1;
					JSONObject data = jsonResponse.getData();
					status = data.getInt(Constant.RESP_STATUS);
					if (status == Constant.RESP_STATUS_SUCCESS) {
						JSONArray jsonArray = data.getJSONArray(Constant.RESP_CIRCLE_MYFRIENDS);

						initFriendItemFromJson(jsonArray);
					}

				}
			} catch (Exception e) {
				// TODO: handle exception

			}
		}
		
		
		
		public void initFriendItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
			Gson gson = new Gson();
			for (int i = 0; i < jsonArray.length(); i++) {
				UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
				Map<String, Object> item = new HashMap<String, Object>();
				item.put("nickname", entity.getUd_nickname());
				item.put("location", entity.getLoc_name());
				item.put("remark", entity.getUd_relname());
				Log.d("Friends", entity.getUd_nickname() + ">>" + entity.getLoc_name() + ">>" + entity.getUd_relname());
				mFriendsItems.add(item);
				friendsPics.put(String.valueOf(i), entity.getUser_avatar());
				friendMap.put(i, entity.getUser_id());
				
			}
		}
	}
